package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"time"
	"xiaohongshu-article/api/request"
	"xiaohongshu-article/consts"
	"xiaohongshu-article/global"
	"xiaohongshu-article/internal/dao"
	"xiaohongshu-article/internal/model"
	"xiaohongshu-article/pkg"
)

func RegisterUser(c *gin.Context) {

	var req request.RegisterUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	dao.GetOneFile(&model.User{Mobile: req.Mobile}, &user)

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "手机号已被使用",
			"data": nil,
		})
		return
	}

	if req.Password != req.PasswordNew {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "两次密码输入不一致",
			"data": nil,
		})
		return
	}

	user = model.User{
		Mobile:   req.Mobile,
		Password: pkg.Md5(req.Password),
		Name:     req.Name,
	}

	dao.AddFile(&user)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": nil,
	})

}

func SendSmsUser(c *gin.Context) {
	var req request.SendSmsForm

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	code := rand.Intn(9000) + 1000
	/*
		err := pkg.SendSms(req.Mobile, strconv.Itoa(code))
		if err != nil {
			return
		}*/

	global.RDB.Set(context.Background(), "sendSms"+req.Mobile, code, time.Minute*3)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "短信发送成功",
		"data": nil,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	get := global.RDB.Get(context.Background(), "sendSms"+req.Mobile)

	if get.Val() != req.Sms {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证码错误,请重新输入",
			"data": nil,
		})
		return
	}

	dao.GetOneFile(&model.User{Mobile: req.Mobile}, &user)

	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "账号或密码错误",
			"data": nil,
		})
		return
	}

	token := pkg.CreateJwtToken(user.Id, 24*time.Hour, consts.JWT_KEY)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登录成功",
		"data": token,
	})
}

func ShowUser(c *gin.Context) {
	var req request.ShowUserForm
	var user model.User

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	dao.GetOneFile(&model.User{Id: req.Id}, &user)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "查看成功",
		"data": user,
	})
}
